import {getNow} from "./common.js";

let defaultState = {
    legacy: true,
    lastTabId: 0,
    countFrom: 0,
    countTo: 0,
    formula: 0,
    sound: 1,
    done: true,
    play: false,
    working: false,
    cancel: false,
    projects: [
        { id: 1, doneBg: "./img/BG01.jpg", className: "simple", color: "#013d99", snd: "./sound/alarm1.mp3", bg: "./img/bg_simple.jpg", icon: "./img/icon_stopwatch.svg", title: "Simple", on: true },
        { id: 2, doneBg: "./img/fall.jpg", className: "fallout", color: "#0e980c", snd: "./sound/mr_stranger.mp3", bg: "./img/bg_fallout_2.jpg", icon: "./img/icon_cowboy_hat.svg", title: "Fallout", on: false },
        { id: 3, doneBg: "./img/BG03.jpg", className: "london", color: "#ba0001", snd: "./sound/bigban.mp3", bg: "./img/bg_london.jpg", icon: "./img/icon_bus.svg", title: "London", on: false },
        { id: 4, doneBg: "./img/BG04.jpg", className: "pokemon", color: "#990001", snd: "./sound/pika_pika.mp3", bg: "./img/bg_game.jpg", icon: "./img/icon_game.svg", title: "Pokemon", on: false },
        { id: 5, doneBg: "./img/BG05.jpg", className: "vader", color: "#00869a", snd: "./sound/vader.mp3", bg: "./img/bg_vader.jpg", icon: "./img/icon_helmet.svg", title: "Vader", on: false },
        { id: 6, doneBg: "./img/BG06.jpg", className: "r2d2", color: "#1f0099", snd: "./sound/r2d2.mp3", bg: "./img/bg_r2d2.jpg", icon: "./img/icon_r2d2.svg", title: "R2D2", on: false },
    ]
};

export function getSettingsSound(){
    let row = currentState.projects.filter(row => row.on).at(0);
    return row.snd;
}
let currentState = defaultState;

export async function dropState(){
    currentState.legacy = true
    await saveState(defaultState)
}

export async function getState(){
    if(currentState.legacy){
        await restoreState();
    }
    return currentState;
}

export async function fetchState(){
    await restoreState();
    return currentState;
}

export async function setDone(){
    if(!currentState.done && currentState.working){
        // await chrome.action.setBadgeText({text: "DONE"});
        await chrome.action.setBadgeText({text: ""});

        currentState.play = true;
        currentState = await saveState(currentState)
        await openTimeTab();
        // playSound();
    }
    currentState.working = false;
    currentState.done = true;
    return await saveState(currentState);
}

export async function setStateMs(ms){
    if(ms>0){
        currentState.done = false;
        currentState.working = true;
    }
    currentState.formula = ms;
    currentState.countFrom = getNow();
    currentState.countTo = (ms * 1) + getNow();
    await saveState(currentState);
    return currentState;
}

export async function incStateMs(ms){
    if(!currentState.countTo || currentState.done || !currentState.working){
        currentState.countTo = getNow();
        currentState.formula = 0;
    }
    if(!currentState.countFrom || currentState.done || !currentState.working){
        currentState.countFrom = getNow();
        currentState.formula = 0;
    }
    if(ms>0){
        currentState.done = false;
        currentState.working = true;
    }
    currentState.countTo += (ms * 1);
    currentState.formula += (ms * 1);

    return saveState(currentState);
}

export function getCountDownPercents(){
    let total = currentState.countTo - currentState.countFrom;
    let current = currentState.countTo - getNow();
    let out = 0;
    if(current > 0){
        out = Math.floor(current * 100/total);
    }
    return out;
}

export function getMsToCountDown(){
    let out = currentState.countTo - getNow();
    if(out<0){
        out = 0;
    }
    return out;
}

export async function dropMs(){
    currentState.working = false;
    currentState.done = false;
    currentState.countTo = 0;
    currentState.countFrom = 0;
    await saveState(currentState);
    return currentState;
}

export async function restoreState(){
    return await chrome.storage.local.get("state").then(savedState => {
        if(savedState){
            try{
                let data = JSON.parse(savedState.state);
                if(data){
                    currentState = data;
                    currentState.legacy = false;
                }
            }catch (e){
                currentState = defaultState;
            }
        }
    });
}

export async function saveState(state){
    state.legacy = true;
    let key = "state";
    let value = JSON.stringify(state);
    state.done = state.countTo <= new Date().getTime;

    return new Promise(async (resolve, reject) => {
        await chrome.storage.local.set({ [key]: value }, () => {
            if (chrome.runtime.lastError) {
                reject("Timer Countdown", chrome.runtime.lastError);
            } else {
                state.legacy = false;
                resolve(state);
            }
        });
    });
}


export async function openTimeTab(){
    let url = chrome.runtime.getURL('alarm.html');
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs.length > 0) {
            if(tabs[0].url !== url){
                currentState.lastTabId = tabs[0].id;
            }
            saveState(currentState);
        }
    });
    await chrome.tabs.query({url: url}).then(tabs => {
        console.log("TARGET URL", tabs[0]);
        if (tabs.length === 0) {
            chrome.tabs.create({
                url: url,
                active: true
            });
        }else{
            let activeTab = tabs[0];
            chrome.tabs.reload(activeTab.id, {}, () => {
                chrome.tabs.update(activeTab.id, { active: true }, () => {
                    console.log(`Tab ${activeTab.id} reloaded and activated.`);
                })
            });
        }
    });
}